package chat.message;

import java.util.Queue;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

public class ChatMessageManager {
    private static volatile boolean isRunning;
    private static AtomicReference<CountDownLatch> listenersLatch = new AtomicReference<CountDownLatch>(new CountDownLatch(1));
    private static AtomicReference<ChatMessage> currentMessage = new AtomicReference<ChatMessage>();
    private static BlockingQueue<ChatMessage> messageQueue = new LinkedBlockingQueue<ChatMessage>();

    public static void start() {
        isRunning = true;
        new Thread(new Runnable() {
            public void run() {
                System.out.println("Begin message processing.");
                try {
                    while(true) {
                        ChatMessage nextMessage = messageQueue.take();
                        if (!isRunning) {
                            break;
                        }
                        CountDownLatch currentLatch = listenersLatch.get();
                        listenersLatch.set(new CountDownLatch(1));
                        currentMessage.set(nextMessage);
                        currentLatch.countDown();
                        Thread.sleep(500);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("Stop message processing.");
            }
        }).start();
    }

    public static void stop() {
        isRunning = false;
        messageQueue.add(new ChatMessage(null, null, null));
        listenersLatch.get().countDown();
    }

    public static ChatMessage getMessage() {
        ChatMessage retVal = null;
        try {
            listenersLatch.get().await();
            retVal = currentMessage.get();
        } catch (InterruptedException e) {
            //ignored
        }
        return retVal;
    }

    public static synchronized void addMessage(ChatMessage newMessage) {
        messageQueue.add(newMessage);
        MessageHistoryManager.addMessage(newMessage);
    }
}
